﻿using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using OnlineStore.Services;
using OnlineStore.Web.Models.ProductDetails;


namespace OnlineStore.Web.Controllers
{
    public class ProductController : Controller
    {
        private readonly IProductService _productService;

        public ProductController(IProductService productService)
        {
            _productService = productService;
        }


        /// <summary>
        /// 对应商品的页面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IActionResult Index(int id)
        {
            var product =  _productService.LoadProductWithDetails(id);
            var model = new ProductDetailsModel {
                product = product,
                products = _productService.GetHotProduct(product.Type)
             };

            return View(model);
        }

        /// <summary>
        /// 用户提交用户点击加入购物车按钮
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        public async Task<IActionResult> AddToCart(int id)
        {
            var claim = HttpContext.User.Claims.FirstOrDefault(c => c.Type == "Id");
            await _productService.AddToCart(id, Convert.ToInt32(claim?.Value));
            return RedirectToAction(nameof(Index), "Product", new { id });
        }
        
    }
}